﻿using System;
using System.Linq;
using Pap.Data.Abstraction.Utils;
using Pap.Services.WorkflowEngine;

namespace Pap.Services.Customer
{
    /// <summary>
    /// 
    /// </summary>
    public class OpenLoans : CustomerValidatorBase
    {
        /// <summary>
        /// 
        /// </summary>
        private IWorkflowService _wfService;
        /// <summary>
        /// Initializes a new instance of the <see cref="OpenLoans"/> class.
        /// </summary>
        /// <param name="_db">The _DB.</param>
        /// <param name="wfService">The wf service.</param>
        public OpenLoans(IDatabase _db, IWorkflowService wfService)
            : base(_db)
        {
            isError = true;
            canValidateByName = false;
            _wfService = wfService;
        }

        /// <summary>
        /// Validates the specified current committee ID.
        /// </summary>
        /// <param name="currentCommitteeID">The current committee ID.</param>
        /// <param name="customer">The customer.</param>
        /// <returns></returns>
        public override bool Validate(Guid currentCommitteeID, Pap.Data.ICustomer customer)
        {
            //int openLoans = (from loan in _database.CustomerLoans
            //             join history in _database.CustomerLoanHistories
            //             on loan.LoanID equals history.LoanID
            //             into g

            //             where loan.CustomerID==customer.CustomerID &&  g.DefaultIfEmpty() == null
            //             select loan).Count();

            var closedLoansIDs = _wfService.GetInStep(Steps.EndedLoans).Union(_wfService.GetInStep(Steps.RefusedLoans)).Union(
                _wfService.GetInStep(Steps.RefusedExecutionList));

            int openLoans = _database.CustomerLoans.Where(
                            loan => loan.CustomerID.Equals(customer.CustomerID) && !closedLoansIDs.Contains(loan.LoanID)).Count();


            if (openLoans > 0)
                return false;
            else
                return true;
        }

        /// <summary>
        /// Validates the specified current committee ID.
        /// </summary>
        /// <param name="currentCommitteeID">The current committee ID.</param>
        /// <param name="customerName">Name of the customer.</param>
        /// <returns></returns>
        public override bool Validate(Guid currentCommitteeID, string customerName)
        {
            throw new Exception("Unsupported. Can't validate for open loan by name only.");
        }
    }
}
